package com.jia.acl.filter;

import com.jia.acl.utils.JwtUtil;
import com.jia.acl.utils.R;
import com.jia.acl.utils.ResponseUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class JWTValidationFilter extends BasicAuthenticationFilter {
    public JWTValidationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
    /*
    * 拦截请求
    * */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            ResponseUtil.out(response, R.error().msg("请传入正确的token"));
        }
        SecurityContextHolder.getContext().setAuthentication(setAuthenticationToken(token));
        super.doFilter(request,response,chain);
    }
    private UsernamePasswordAuthenticationToken setAuthenticationToken(String token) {
        String username = JwtUtil.getUsername(token);
        if (!StringUtils.isEmpty(username)){
            // 解析权限列表
            List<SimpleGrantedAuthority> userRoles = JwtUtil.getUserRoles(token);
            return new UsernamePasswordAuthenticationToken(username,null,userRoles);
        }
        return null;
    }
}
